import datetime
import re

from exts import db
from models import Category


def add_category(user_id, username, category_name, category_alias):
    category = Category.query.filter_by(category_name=category_name).first()
    if category:
        raise Exception("文章分类已存在")

    if not re.findall(r".{1,32}", category_name):
        raise Exception("文章分类名不合法，长度应在1-32位之间")

    if not re.findall(r".{1,32}", category_alias):
        raise Exception("文章分类别名不合法，长度应在1-32位之间")

    category = Category(create_user_id=user_id,
                        create_user_name=username,
                        category_name=category_name,
                        category_alias=category_alias,
                        create_time=datetime.datetime.now(),
                        update_time=datetime.datetime.now())

    db.session.add(category)

    try:
        db.session.commit()
        return True
    except Exception as ex:
        raise ex


def get_category():
    category_list = Category.query.all()
    category_list = [category.to_dict() for category in category_list]
    return category_list


def update_category(category_id, category_name, category_alias):
    category = Category.query.filter_by(category_id=category_id).first()

    if not category:
        raise Exception("文章类别不存在")

    if category_name:
        if not re.findall(r".{1,32}", category_name):
            raise Exception("文章分类名不合法，长度应在1-32位之间")
        category.category_name = category_name

    if category_alias:
        if not re.findall(r".{1,32}", category_alias):
            raise Exception("文章分类别名不合法，长度应在1-32位之间")
        category.category_alias = category

    category.update_time = datetime.datetime.now()

    try:
        db.session.commit()
        return True
    except Exception as ex:
        raise ex


def delete_category(category_id):
    category = Category.query.filter_by(category_id=category_id).first()

    if not category:
        raise Exception("文章类别不存在")

    db.session.delete(category)
    try:
        db.session.commit()
        return True
    except Exception as ex:
        raise ex
